package com.kiell.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.kiell.common.es.SkuEsModel;
import com.kiell.gulimall.search.config.GulimallElasticSearchConfig;
import com.kiell.gulimall.search.constant.EsConstant;
import com.kiell.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Created: with IntelliJ IDEA.
 * @author: kiell
 * @createTime: 2024年3月7日15:47:53
 **/

@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient esRestClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        //1.在es中建立索引，建立号映射关系（doc/json/product-mapping.json）

        //2. 在ES中保存这些数据//批量操作
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }


        BulkResponse bulk = esRestClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        //TODO 如果批量错误
        boolean hasFailures = bulk.hasFailures();

        List<String> collect = Arrays.asList(bulk.getItems()).stream().map(item -> {
            return item.getId();
        }).collect(Collectors.toList());

        log.info("商品上架完成：{},返回数据:{}",collect,bulk.toString());

        return hasFailures;
    }

    /**
     * @param spuId
     * @return
     */
    @Override
    public boolean productStatusDown(Long spuId) throws IOException {
        // 初始化Elasticsearch客户端

        // 创建删除请求
        DeleteByQueryRequest request = new DeleteByQueryRequest(EsConstant.PRODUCT_INDEX); // 替换为你的索引名

        // 设置查询条件
        request.setQuery(QueryBuilders.termQuery("spuId", spuId)); // 替换为你的字段名和值

        // 执行删除操作
        BulkByScrollResponse response = esRestClient.deleteByQuery(request, GulimallElasticSearchConfig.COMMON_OPTIONS);

        // 输出结果
        System.out.println("Deleted: " + response.getDeleted());
        System.out.println("Failures: " + response.getBulkFailures().size());
        System.out.println("Timeouts: " + response.getSearchFailures().size());

        if (response.getDeleted() > 0){
            return true;
        }
        return false;
    }
}
